// StockTicker.jsx
import React, { useEffect, useState } from 'react'
import axios from 'axios'
import './StockTicker.scss'

// 可修改为后端或配置动态传入的股票列表
const SYMBOLS = [
  'sh600000', 'sh601398', 'sz000001', 'sz000002', 'sh600519'
]

const StockTicker = () => {
  const [quotes, setQuotes] = useState([])

  const fetchQuotes = async () => {
    try {
      const responses = await Promise.all(
        SYMBOLS.map(sym =>
          axios.get('/api/stock/info', { params: { symbol: sym } })
        )
      )
      const data = responses.map((res, i) => {
        const list = res.data.data
        const latest = list.find(item => item.item === '最新')
        return {
          symbol: SYMBOLS[i].replace(/^(sh|sz)/, ''),
          price: latest ? latest.value : '--'
        }
      })
      setQuotes(data)
    } catch (e) {
      console.error('[StockTicker] fetch error', e)
    }
  }

  useEffect(() => {
    fetchQuotes()
    const timer = setInterval(fetchQuotes, 30000) // 30 秒刷新一次
    return () => clearInterval(timer)
  }, [])

  return (
    <div className="ticker-container">
      <div className="ticker-track">
        {quotes.map(q => (
          <span key={q.symbol} className="ticker-item">
            {q.symbol}: {q.price}
          </span>
        ))}
      </div>
    </div>
  )
}

export default StockTicker